<template>
  <div>
    <HfBatchSelectTransfer
      ref='batchSelectTransferRef'
      :data-url='dataUrl'
      :loading='loading'
      @change='handleDataChange'
    >
      <template #action>
        <a-space>
          <a-button type='primary' @click="handleGenerate('100x80')">
            生成标签(100x80)
          </a-button>
          <a-button type='primary' @click="handleGenerate('2x2')">
            生成标签(2x2)
          </a-button>
          <a-button type='primary' @click="handleGenerate('2x3')">
            生成标签(2x3)
          </a-button>
          <a-button icon='reset' type='primary' @click='handleReset()'>
            重置
          </a-button>
        </a-space>
      </template>
    </HfBatchSelectTransfer>
  </div>
</template>

<script>
import HfMaterialSearchSelectTag from '@comp/HfManual/HfMaterialSearchSelectTag.vue'
import { downloadFile, postAction } from '@api/manage'
import HfBatchSelectTransfer from '@comp/HfManual/HfBatchSelectTransfer.vue'

export default {
  name: 'BatchGenerateBarcode',
  components: {
    HfBatchSelectTransfer,
    HfMaterialSearchSelectTag
  },
  props: {
    dataUrl: {
      type: String,
      default: '',
      required: true
    }
  },
  data() {
    return {
      loading: false,
      url: {
        batchGenerateCode: {
          '100x80': '/label/generateBatchBarcode',
          '2x2': '/label/generateBatchBarcodeA4Large',
          '2x3': '/label/generateBatchBarcodeA4Small'
        }
      },
      selectedData: []
    }
  },
  watch: {},
  methods: {
    handleDataChange(data) {
      this.selectedData = data
    },
    handleGenerate(type) {
      this.loading = true
      if (this.selectedData.length === 0) {
        this.$message.error('请选择要打印的标签数据！！！')
        this.loading = false
        return
      }
      const form = this.selectedData.map(item => {
        return {
          materialCode: item.materialCode,
          materialName: item.materialName,
          customName: item.customId_dictText,
          perNumber: item.perNumber,
          qad: item.qad,
          saleCode: item.saleCode,
          saleCode1: item.saleCode1
        }
      })
      const url = this.url.batchGenerateCode[type]
      
      postAction(url, form, { timeout: 0 })
        .then(res => {
          if (res.success) {
            downloadFile(res.result.url, `${res.result.pdfName}.pdf`)
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleReset() {
      this.$refs.batchSelectTransferRef.handleReset()
    }
  }
}
</script>
<style scoped></style>
